<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/08/18
 */
namespace api\modules\mp\models;

use common\tool\Curd;
use yii\base\Model;
use yii\web\NotFoundHttpException;

class Transfer extends Model {
    use Curd;
    public static function tableName() {
        return 'mp_transfer';
    }

    public function rules(){
        return [
            [['title','stime','etime','price','place'],'required'],
            [['title','description','openid','pics'],'string'],
            [['stime','etime','ctime','utime'],'datetime','format' => 'yyyy-MM-dd HH:mm:ss'],
            [['oldPrice','price'],'number','min'=>0],
            [
                'object',
                'number',
                'min' => 0,
                'max' => 2
            ],
            [
                'status',
                'number',
                'min' => 1,
                'max' => 3
            ],
        ];
    }

    public static function build($data = []): ?self {
        if (!empty($data['id'])) {
            $one = self::getOne("id={$data['id']}");
            if (!$one) throw new NotFoundHttpException();
            $data = array_merge($one, $data);
        }
        return new self($data);
    }

    public $id;
    public $title;
    public $openid;
    public $stime;
    public $etime;
    public $description;
    public $price;
    public $oldPrice;
    public $place;
    public $object = self::OBJECT_NONE;
    public $pics;
    public $ctime;
    public $utime;
    public $status = self::STATUS_PUBLISH;
    const OBJECT_MALE = 1;
    const OBJECT_FEMALE = 2;
    const OBJECT_NONE = 0;//不限制约伴对象
    const STATUS_DRAFT = 1;
    const STATUS_PUBLISH = 2;
    const STATUS_CANCEL = 3;

    public function save() {
        $data = [
            'title' => $this->title,
            'openid' => $this->openid,
            'stime' => $this->stime,
            'etime' => $this->etime,
            'description' => $this->description ?: '',
            'place' => $this->place,
            'object' => $this->object,
            'pics' => $this->pics ?: '',
            'status' => $this->status,
        ];
        $now = date('Y-m-d H:i:s');
        if ($this->id) {
            $data['utime'] = $now;
            self::update($data, 'id=:id', [':id' => $this->id]);
        } else {
            $data['ctime'] = $data['utime'] = $now;
            $id = self::insert($data);
            $this->id = $id;
        }
        return ['err' => 0];
    }

    public function publish() {
        return self::update(['status' => self::STATUS_PUBLISH], 'id=:id', [':id' => $this->id]);
    }

    public function cancel() {
        return self::update(['status' => self::STATUS_CANCEL], 'id=:id', [':id' => $this->id]);
    }

    public function info() {
        $r = get_object_vars($this);
        $res = [];
        foreach ($r as $k => $v) {
            $res[substr($k, 1)] = $v;
        }
        return $res;
    }
}
